var bletools = require('../../utils/blue.js');
var constants = require('../../utils/constants.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    mark: 0,
    res: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  getInputValue(e) {
    this.setData({
      name: e.detail.value
    })
  },
  opendoor(e) {
    if (!this.data.name) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '编码未填写。',
      })
      return;
    }
    bletools.initBluetooth(this)
  },

  /**
 * ble状态监听
 */
  bleStateListener: function (state) {
    let that = this;
    switch (state) {
      case constants.NOT_BLE_STATUS:
        console.log('走udp')
        // 蓝牙从一开始就没打开
        if (that.data.mark == 0) {
          //未开锁走udp
          that.updConnection()
        } else {
          //开锁状态 轮询是否关锁
          that.searchLock()
        }
        break;
      case constants.LOW_BLE_STATUS:
        //蓝牙版本低
        showModal(constants.LOW_BLE)
        break;
      case constants.NOT_LONG_BLE_STATUS:
        //蓝牙在使用中断开
        showModal(constants.NOT_LONG_BLE)
        break;
      case constants.OPEN_LOCK_ALARM_STATUS:
        //锁开启失败
        showModal(constants.OPEN_LOCK_ALARM)
        break;
      case constants.CLOSE_LOCK_ALARM_STATUS:
        //锁关闭失败
        showModal(constants.CLOSE_LOCK_ALARM)
        break;
      case constants.SUCCESS_LOCK_STATUS:
        //开锁成功
        that.successLock()
        break;
      case constants.OPEN_BLE_STATUS:
        //蓝牙正常开启（只打印）
        console.log(constants.OPEN_BLE)
        break;
      case constants.NORMAL_LOCK_STATUS:
        //设备状态正常
        that.creatPay(1)
        break;
      case constants.CLOSE_LOCK_STATUS:
        //蓝牙关锁成功
        that.closeLock()
        break;
      case constants.OTHER_STATUS:
        //某些原因开锁失败
        showModal(constants.OTHER)
        break;
      case constants.NO_SEARCH_BLE_STATUS:
        //搜索蓝牙失败
        showModal(constants.NO_SEARCH_BLE)
        break;
      case constants.NO_RES_STATUS:
        //搜索蓝牙失败
        showModal(constants.NO_RES)
        break;
      default:
        showModal(state)
        break;
    }
  },

  /**
   * 创建订单
   * @param {*} flag 
   */
  creatPay(flag) {
    let that = this;
    let ble = bletools;
    wx.request({
      method: "POST",
      header: { 'content-type': 'application/json' },
      url: 'https://care.hhx06.top/api/creatPay',
      data: {
        name: 'test',
        money: 1,
        number: that.data.name,
        imei: that.data.name,
      },
      success: function (uu) {
        if (uu.data.code == '100100') {
          if (flag == 1) {
            setTimeout(() => {
              ble.writeBluetoothCharacteristicValue(uu.data.token, 1)
            }, 20)
          } else {
            setTimeout(() => {
              that.searchResult()
            }, 20000)
          }
        } else {
          wx.showModal({
            title: '提示',
            content: '订单失败',
            showCancel: false
          })
        }
      }
    })
  },

  /**
   * 查询设备开锁结果
   */
  searchResult() {
    let that = this;
    wx.request({
      method: "get",
      header: { 'content-type': 'application/json' },
      url: 'https://care.hhx06.top/api/searchResult',
      data: {
        number: that.data.name,
      },
      success: function (uu) {
        if (uu.data.code == '100100') {
          that.setData({
            mark: 1
          })
          wx.showModal({
            title: '提示',
            content: '开锁成功',
            showCancel: false
          })
          that.setIntervals()
        } else {
          wx.showModal({
            title: '提示',
            content: '开锁失败1',
            showCancel: false
          })
        }
      }
    })
  },

  /**
   * 走udp协议
   */
  updConnection() {
    let that = this;
    // this.data.name
    wx.request({
      method: "GET",
      header: { 'content-type': 'application/json' },
      url: 'https://care.hhx06.top/api/SearchDeviceStatus',
      data: {
        number: this.data.name,
      },
      success: function (uu) {
        if (uu.data.code == '100100') {
          that.creatPay(2)
        } else {
          wx.showModal({
            title: '提示',
            content: '请打开蓝牙或电量按钮重试',
            showCancel: false
          })
        }
      }
    })
  },

  /**
   * 锁关闭蓝牙传输
   */
  closeLock() {
    let that = this;
    wx.request({
      method: "POST",
      header: { 'content-type': 'application/json' },
      url: 'https://care.hhx06.top/api/closeLock',
      data: {
        number: that.data.name,
        imei: that.data.name,
      },
      success: function (uu) {
        if (uu.data.code == '100100') {
          that.setData({
            mark: 0
          })
          wx.showModal({
            title: '提示',
            content: '关锁成功（后续更新锁状态）',
            showCancel: false
          })
        }
      }
    })
  },
  /**
   * 轮询查看锁是否关闭
   */
  searchLock() {
    let that = this;
    wx.request({
      method: "GET",
      header: { 'content-type': 'application/json' },
      url: 'https://care.hhx06.top/api/searchLock',
      data: {
        number: this.data.name,
      },
      success: function (uu) {
        if (uu.data.code == '100100') {
          console.log('ok')
          that.setData({
            mark: 0,
            res: 1
          })
        }

      }
    })
  },

  /**
   * 开锁成功
   */
  successLock() {
    let that = this;
    wx.request({
      method: "POST",
      header: { 'content-type': 'application/json' },
      url: 'https://care.hhx06.top/api/successLock',
      data: {
        number: that.data.name,
        imei: that.data.name,
      },
      success: function (uu) {
        if (uu.data.code == '100100') {
          that.setData({
            mark: 1
          })
          wx.showModal({
            title: '提示',
            content: '开锁成功（后续更新锁状态）',
            showCancel: false
          })
        }
      }
    })
  },

  setIntervals() {
    let that = this;
    var times = 0
    var i = setInterval(function () {
      times++
      if (times >= 30) {
        clearInterval(i)
      } else {
        that.searchLock()
        if (that.data.res > 0) {
          wx.showModal({
            title: '提示',
            content: '关锁成功（后续更新锁状态）',
            showCancel: false
          })
          clearInterval(i)
        }
      }
    }, 2000)
  }
})

/**
 * 对一些告警信息弹窗显示
 */
function showModal(content) {
  wx.showModal({
    title: constants.ALARM_TITLE,
    content: content,
    showCancel: false,
  })
}

function successModal(content) {
  wx.showModal({
    title: constants.SUCESS_TITLE,
    content: content,
    showCancel: false,
  })
}
